<%@ page import="br.com.rosena.model.bean.persistente.Persistente" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="br.com.rosena.control.ControllerRosena" %>
<%@ page import="br.com.rosena.model.dao.padrao.RotearBD" %>
<%
    String login = request.getParameter("txtUsuario");
    String senha = request.getParameter("txtSenha");
    String idConfiguracao = request.getParameter("txtConfiguracao") != null ? request.getParameter("txtConfiguracao") : "1";

    Persistente objUsuario = new Persistente("Usuario");
    objUsuario.setString("descricao",login);
    objUsuario.setString("senha",br.com.rosena.util.Util.encriptar(senha.trim()));
    boolean validade = ((Boolean) objUsuario.invocarMetodo("validarSenha")).booleanValue();
%>
<%if (validade) {
    ResultSet crs = new ControllerRosena().execultarQueryReturResultSet("SELECT CG.ID,  CG.descricao, CG.configuracaovenda , F.ID AS idFilial, F.descricao As descricaoFilial  FROM ConfiguracaoGeral CG , filial F  WHERE CG.Filial = F.ID AND CG.ID = '" + idConfiguracao + "'");
    if (crs.next()) {
        ResultSet crsUsuario = new ControllerRosena().execultarQueryReturResultSet("SELECT U.ID FROM USUARIO U WHERE U.DESCRICAO = '" + login + "'");
        if (crsUsuario.next()) {
            objUsuario = new Persistente("Usuario", new Long(crsUsuario.getString("ID")).longValue());
        } else {
            throw new Exception("Problema no login, entre em contato");
        }
        Persistente objFilial = new Persistente("Filial", crs.getLong("idFilial"));
        session.setAttribute("ID_Usuario", new Long(objUsuario.getId()));
        session.setAttribute("USUARIO", objUsuario);
        session.setAttribute("FILIAL", objFilial);
        session.setAttribute("session", session.getId());

        session.setAttribute("WEBSITE", RotearBD.getSistema().getWEBSITE());
        session.setAttribute("WEBSITEJAVASCRIPT", RotearBD.getSistema().getWEBSITEJAVASCRIPT() );
        br.com.rosena.util.Util.setWebSite(RotearBD.getSistema().getWEBSITE() );


        if(!RotearBD.getSistema().isCONFIGURARPROTOCOLOAUTOMATICO() ){
            br.com.rosena.util.Util.setProtocolo(RotearBD.getSistema().getPROTOCOLO() );
            br.com.rosena.util.Util.setRemoteAddR(RotearBD.getSistema().getREMOTEADDR() );
            br.com.rosena.util.Util.setRemotHost(RotearBD.getSistema().getREMOTHOST() );
        }else{
             br.com.rosena.util.Util.setProtocolo(request.getProtocol());
            br.com.rosena.util.Util.setRemoteAddR(request.getRemoteAddr());
            br.com.rosena.util.Util.setRemotHost(request.getRemoteHost());
        }

    }%>
    <%response.sendRedirect("principal.jsp");%>
<%}else{%>
    <%response.sendRedirect("index.jsp?error=INVALID LOGIN");%>
<%}%>